package org.anyin.gitee.cloud.center.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.anyin.gitee.cloud.center.common.constants.CommonConstants;
import org.anyin.gitee.cloud.lib.core.utils.RequestIdUtil;
import org.anyin.gitee.cloud.lib.core.web.context.WebContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

public class FeignRequestInterceptor implements RequestInterceptor {

    @Value("${spring.application.name}")
    private String app;

    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest request = WebContext.getRequest();
        // job 类型的任务，可能没有Request
        if(request != null && request.getHeaderNames() != null){
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                // 避免传递其他格式的数据
                if ("Accept".equalsIgnoreCase(name)) {
                    continue;
                }
                String values = request.getHeader(name);
                template.header(name, values);
            }
        }

        template.header(CommonConstants.APPLICATION_NAME, app);
        template.header(CommonConstants.REQUEST_ID, RequestIdUtil.getRequestId().toString());
        template.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    }
}
